<template>
  <view class="wordGuess" :style="{'background':sportData.settings.bgcolor}">
    <div class="headerBanner">
      <image class="banner" :mode="'widthFix'" :src="sportData.settings.banner"></image>
    </div>
	<div class="red_package" v-if="showHasAward">
		<div @click.stop="showModal('myGuess')">你有<span>&nbsp; {{has_award}} &nbsp;</span>个待领红包，<span class="click_href">点我去领取</span></div>
		<div @click.stop = "showHasAward=false">X</div>
	</div>
    <div class="right_button">
      <div class="button_area" @click="showModal('share')">
        <image class="button_img" :mode="'scaleToFill'" :src="share_icon"></image>
      </div>
      <div class="button_area" @click="showModal('myGuess')">
        <div class="red_point" :class="{'red_point_ny':skinType==6} " v-if="has_award>0"></div>
        <image class="button_img" :mode="'scaleToFill'" :src="winner_icon"></image>
      </div>
      <div class="button_area" @click="showModal('rule')">
        <image class="button_img" :mode="'scaleToFill'" :src="rule_icon"></image>
      </div>
	  <div class="button_area" v-if="advSet.open_ranking" @click="showModal('sort')">
	    <image class="button_img" :mode="'scaleToFill'" :src="sort_icon"></image>
	  </div>
    </div>
    <div class="sports_area">
      <div class="sports_info" v-if="sportData.settings.show_data">
        <div class="view_num">浏览量<span>{{ basicData.view_num }}</span>次</div>
        <div class="play_num">参与数<span>{{ basicData.play_num }}</span>人</div>
      </div>
      <div class="sports_tab">
        <div class="tab_one" :class="{'tab_one_choosed':tabType == 0 && skinType==null,'new_year_tabcolor':tabType == 0 && skinType==6}" @click="changeGameType(0)">未开始</div>
        <div class="tab_one" :class="{'tab_one_choosed':tabType == 1 && skinType==null,'new_year_tabcolor':tabType == 1 && skinType==6}" @click="changeGameType(1)">进行中</div>
        <div class="tab_one" :class="{'tab_one_choosed':tabType == 2 && skinType==null,'new_year_tabcolor':tabType == 2 && skinType==6}" @click="changeGameType(2)">已结束</div>
      </div>
      <div class="sports_list" :class="{'no_sports_list':0 == sportsList.length}">
        <div class="sports_detail"  v-for="(item,index) in sportsList" @click="goDetail(item.id,item.award_status,sportsList.length)">
          <div class="sports_header" :class="{'sports_header_ny':skinType==6}">
            <div class="dots"></div>
            <div class="timeDetail">{{item.time_show}}</div>
            <div class="dots"></div>
			<div class="sports_header_bg"  v-if="skinType==6">
				<img src="../../../static/sports/home_list_header.png" alt="">
			</div>
          </div>
          <div class="sports_content" :class="{'sports_content_ny':skinType==6}">
            <div class="sports_sponsor" v-if="item.sponsors.length != 0">
              <div class="sponsor_name" v-for="(itemSp,index) in item.sponsors">
                <span>{{ itemSp }}</span> <span style="color:#000000" v-if="(index+1) != item.sponsors.length">＆</span>
              </div>
              <!--              <div class="sponsor_name">
                              <span>鹏宇设计</span>
                            </div>-->
              赞助本场奖励
            </div>
            <div class="sports_title">
              <image class="title_img" :src="guafen_img" :mode="'scaleToFill'"></image>
            </div>
            <div class="sports_award">
              <div class="number_area">
                <div class="number_show"  v-for="(itemReward,index) in item.jackpot_list" :class="{'noMargin': index+1 ==item.jackpot_list.length,'number_show_ny':skinType==6}">{{itemReward}}</div>
                <div class="number_unit">元</div>
              </div>

            </div>
            <div class="sports_word">
              {{ item.title }}
            </div>
            <div class="sports_team" v-if="item.teams.length != 0">
              <div class="team_one_outer" v-for="(itemTeam,indexTeam) in item.newTeam">
                <div class="team_one_position" :class="{' team_one_position_left':0 == indexTeam,' team_one_position_right':1 == indexTeam}">
                  <div class="team_one">
                    <div class="team_icon">
                      <image class="team_icon_img" :mode="'scaleToFill'" :src="itemTeam.logo+'?imageView/1/w/200/h/200'"></image>
                    </div>
                    <div class="team_name">{{ itemTeam.name }}</div>
                  </div>
                </div>

              </div>
              <!--              <div class="team_one_outer">
                              <div class="team_one">
                                <div class="team_icon"></div>
                                <div class="team_name">沙特阿拉哥斯达黎加伯</div>
                              </div>
                            </div>-->
            </div>
			<div v-if="skinType==6 && item.image!=''" class="sport_meida">
				<img v-if="checkType(item.image)=='image'" :src="item.image" alt="">
				<div v-if="checkType(item.image)=='video'" class="videoBox">
					<img  :src="item.image+'?vframe/png/offset/2'" alt="">
				</div>
				
				<!-- <video v-if="checkType(item.image)=='video'" :show-center-play-btn="false" :src="item.image" :enable-progress-gesture="false" :controls="false"> </video> -->
			</div>
            <div class="enter_button" @click="goDetail(item.id,item.award_status,sportsList.length)" :class="{'no_enter':tabType != 1,'enter_button_ny':skinType==6}" v-if=" tabType != 0">
              <span v-if="tabType == 1">参加竞猜</span>
              <span v-if="tabType == 2 && item.award_status == 0">等待开奖</span>
              <span v-if="tabType == 2 && item.award_status == 1">已结束</span>
            </div>
          </div>
        </div>
        <noResult ref="message" v-if="0 == sportsList.length && !loading" :text="noMessage"></noResult>
        <div class="more_button" v-if="noMore" @click="showMore()">
          <image class="more_icon" :mode="'scaleToFill'" src="~@/static/sports/more_sports.png"></image>
          <span class="more_text">更多竞猜</span>
        </div>
      </div>
	  <div class="service_con" v-if="advSet.service_open">
		  <service ></service>
	  </div>
      <div class="sports_swiper" v-if="sportData.settings.bottom_ads.length!=0&&sportData.settings.bottom_ad_open==true">
        <swiper class="swiper" circular :indicator-dots="indicatorDots" :autoplay="autoplay" :current="currentIndex">
          <swiper-item v-for="(item,index) in sportData.settings.bottom_ads" >
            <div class="swiper_content" @click="jumpNew(item.link)">
              <image  v-if="checkType(item.image)=='image'" class="swiper_img" :mode="'scaleToFill'" :src="item.image"></image>
			  <video class="swiper_video" v-if="checkType(item.image)=='video'" :src="item.image" :enable-progress-gesture="false" controls>
				</video>
            </div>
          </swiper-item>
        </swiper>
      </div>
      <div class="bottom_text">
        {{ sportData.settings.copyright }}
      </div>
    </div>
    <div class="mission_button">
      <image class="mission_img" :src="sportData.settings.task_float" @click="showModal('mission')"></image>
    </div>
    <guessRule :rule="sportData.activity_rules" v-if="showRuleModal" @hideRuleModal="hideModal"></guessRule>
	  <taskCenter :act_type="'sports'" :show="showTask" :topImage="advSet"  :list="taskMenuData" @close="handlerCloseTaskCenter" @finish="handlerTaskFinish" v-if="showTask"></taskCenter>
    <help :data="advSet" v-if="showHelpModal" @hideMissionModal="hideModal"></help>
    <advertise :data="advSet" @close="closeAdv"></advertise>
    <share v-if="showShare" :data="shareData" @close="showShare=false"></share>
    <guide></guide>
    <sportsModal :act_type="act_type" @hideToastModal="hideToastModal" v-if="toastModal"></sportsModal>
  </view>
</template>

<script>
import guessRule from "../../../components/worldGuess/guessRule";
import sportsModal from "../../../components/worldGuess/sportsModal";
import help from "../../../components/taskCenter/help";
import advertise from '@/components/advertise/advertise'
import share from '@/components/share/share'
import noResult from "../../../components/worldGuess/noResult";
import {guessSportsList, guessSportsInfo, guessSportsText, getIfCanRelay, getIfHasReward,taskList} from "../../../api/api";
import {timeStampToString} from '@/until/tool'
import {LoginApp,checkLogin,isWeiXin,isQianfan,checkPlatform,proxyShareFun,newJumpUrl,checkLoginBefore,countNum} from '@/until/QFH5.js'
import {mapState,mapGetters} from "vuex";
import watermarkOption from '@/until/water.js'
import * as frameJs from '@/model/frameData'
import {formatTime} from '@/until/tool'
export default {
  name: "worldGuess",
  data() {
    return {
      indicatorDots: false,
      autoplay: true,
      disable: true,
      currentIndex: 0,
      showRuleModal: false,
      showMyGuessModal: false,
      showTask: false,//任务
      showHelpModal: false,
      noMore:false,
      loading:true,

      /*兑奖参数*/
      has_award:0,
	  showHasAward:false,
      /*广告参数*/
      advSet: {},

      /*分享参数*/
      shareData: {},
      showShare: false,//分享


      /*活动相关参数*/
      sportData: {},
      basicData: {},
      choosedType: 1,
      actid: '',
      sportsList: [],
      moreList:[],
      cursor: 0,
      tabType: 1,
      noMessage:'还没有进行中的竞猜哦~',
      toastModal:false,
      act_type:-1,

      taskMenuData:[],
      isframe:false,
      race_id:this.$store.state.race_id,
	  share_icon:require('@/static/sports/share_act.png'),
	  winner_icon:require('@/static/sports/win_record.png'),
	  rule_icon:require('@/static/sports/act_rules.png'),
	  sort_icon:require('@/static/sports/sorts_icon.png'),
	  guafen_img:require('@/static/sports/sports_win.png')
    }
  },
  components: {
    guessRule,
    help,
    advertise,
    share,
    noResult,
    sportsModal
  },
  computed:{
    ...mapState({
      guide:state => state.guide,
	
    }),
	...mapGetters(['updateTask','skinType'])
  },

  methods: {
	checkType(val){
	    return this.$checkType(val)
	},
	 
    async initBefore(){
      let res = {}
      if(!this.isframe){
        res = await guessSportsInfo({actid: this.actid})
      }
      this.sportData = res.data
      this.shareData = res.data
      uni.setStorageSync('actid', this.actid)
      uni.setStorageSync('platform',JSON.stringify(res.data.settings.platform))
      if(await checkLoginBefore()){
        await this.initData(res)
      }
    },
    async initSportsData(data = null) {
      let res = data
      if(!this.isframe){
        res = await guessSportsInfo({actid: this.actid})
      }
      if(0 == res.data.status){
        watermarkOption.set('活动未发布')
      }
      this.$setTitle(res.data.title)
      if(parseInt(new Date().getTime()/1000) < res.data.start_time){
        this.toastModal = true
        this.act_type = 0
      }else if(parseInt(new Date().getTime()/1000) > res.data.expire_time){
        this.toastModal = true
        this.act_type = 1
      }
      uni.setStorageSync('title',res.data.title)
      this.sportData = res.data
	  
	  let _this = this
	  this.$nextTick(()=>{
		  let token = localStorage.getItem(_this.actid+'bearerToken') || null
		  if(token!=null && _this.$store.state.long==0 && _this.$store.state.lat==0  &&_this.sportData.area && _this.sportData.area.type==3){
			_this.$store.dispatch('getPos')
			window.getLocationCallBackFun=()=>{}
		  }
	  })
      uni.setStorageSync('shareImg', res.data.settings.poster)
      uni.setStorageSync('image', res.data.settings.image)
      this.advSet = res.data.settings
      this.shareData = res.data
	  this.$store.dispatch('serviceInfo', res.data.settings)
      uni.setStorageSync('platform',JSON.stringify(res.data.settings.platform))
  
		let loactionUrl = window.location.href
       
        let dataShare =  res.data
		proxyShareFun(dataShare.settings.title,dataShare.settings.image,dataShare.settings.desc,loactionUrl)
		
        this.$nextTick(() => {


        })
	  
      if(this.isframe){
          /*更改一些数据触发的部分操作*/
          /*if(res.data){

          }*/
        this.basicData = data.data
        return
      }
	  
      await this.getBasicData()
      //登录在查询
      let loginStatus = await checkLogin()
      if(loginStatus){
        if(isQianfan()){
          let {isWechat,phone} = this.guide
          if(!isWechat){
            this.$store.dispatch('setGuideShow',1)
            return
          }
          else if(phone==""){
            this.$store.dispatch('setGuideShow',2)
            return
          }else{
            this.getIfHasPlay()
          }
        }else{
          this.getIfHasPlay()
        }

      }

      
      /*this.initTask()*/
    },
    //任务
    async initTask(){
      let res = await taskList({actid:this.actid})
      this.taskMenuData = res.data
      this.showTask = true
      /*taskList({actid:this.actid}).then(res=>{
        this.taskMenuData = res.data
      })*/
    },
    //关闭任务
    handlerCloseTaskCenter(val){
      if(!this.isframe){
        this.showTask = val
      }

    },
    //完成任务
    handlerTaskFinish(val){
      if(val && val.type=='share')
        this.showShare = true
      this.initTask()
    },
    getIfHasPlay(){
      getIfHasReward({actid: this.actid}).then(res=>{
        this.has_award = res.data.has_award
        if(res.data.has_award>0){
          this.showHasAward = true
        }else{
		  this.showHasAward = false
		}
      })
    },
    async getBasicData() {
      if(!this.isframe){
        let res = await guessSportsText({actid: this.actid})
        this.basicData = res.data
      }
      this.getSportsList()
    },
    getSportsList() {
      let data = {
        actid: this.actid,
        state: this.tabType
      }
      guessSportsList(data).then(res => {
        let _this = this
        let list = res.data.result
        _this.loading = false
        /*_this.sportsList = res.data.result*/
        _this.moreList = []
        list.forEach(item=>{
          let newList = _this.numBerFormat(item.jackpot)
          if(0!=item.teams.length){
            let team_a = item.team_a
            let team_b = item.team_b
            let team_a_obj = {}
            let team_b_obj = {}
            let listTeam = []
            item.teams.forEach(itemTeam=>{
              if(team_a == itemTeam.id){
                team_a_obj = itemTeam
              }
              if(team_b == itemTeam.id){
                team_b_obj = itemTeam
              }
            })
            listTeam.push(team_a_obj)
            listTeam.push(team_b_obj)
            item.newTeam = listTeam
          }
          item.jackpot_list = newList
          let set = {
            showHour: true,
            showMin: true,
            showSec: false,
            showWeek: true
          }
          item.time_show =''+ formatTime(item.guess_start, 'MM-DD HH:MM')+' - '+formatTime(item.guess_stop, 'MM-DD HH:MM')
        })
        if(list.length > 8){
          _this.moreList = list.slice(8,list.length)
          _this.sportsList = list.slice(0,8)
          _this.noMore = true
        }else{
          _this.sportsList = list
          _this.noMore = false
        }
        _this.sportsList.forEach((itemList,index)=>{
          /*重新组装*/
          if(itemList.id == _this.race_id){
              _this.sportsList.splice(index,1)
            _this.sportsList.unshift(itemList)

          }
        })
        /*如果在第二页*/
        _this.moreList.forEach((itemMore,indexMore)=>{
            /*重新组装*/
            if(itemMore.id == _this.race_id){
                _this.sportsList.unshift(itemMore)
                _this.moreList.splice(indexMore,1)
                _this.moreList.unshift(_this.sportsList[_this.sportsList.length-1])
                _this.sportsList.splice(_this.sportsList.length-1,1)
            }
        })
      })

    },
    showMore(){
      this.sportsList = this.sportsList.concat(this.moreList)
      this.noMore = false
    },
    goSportsDetail(id) {
      /*let data = {

      }
      guessSportsDetail().then*/
    },
    numBerFormat(number) {
      let numberText = number + ''
      return numberText.split("")
    },
    async changeGameType(type) {
      this.basicData = await countNum(this.actid)
      this.tabType = type

      /*this.noMessage = '还没有进行中的竞猜哦~'*/
      if(0 == this.tabType){
        this.noMessage = '还没有未开始的竞猜哦~'
      }
      if(1 == this.tabType){
        this.noMessage = '还没有进行中的竞猜哦~'
      }
      if(2 == this.tabType){
        this.noMessage = '还没有结束的竞猜哦~'
      }
      this.getSportsList()
    },
    goDetail(id,status,listLength) {
      if(this.act_type == 0 || this.act_type == 1){
        this.toastModal = true
        return;
      }
      if(this.tabType == 2){
        uni.showToast({ title:'活动已结束', icon:'none' })
        return;
      }else{
        let callback=()=>{
          uni.navigateTo({
            url: "/plugin/pages/sports/guessDetail?race_id=" + id+'&id='+this.actid+'&listLength='+listLength,
          });
        }
        this.getAuth(callback,null,true)
      }

    },
    async showModal(type) {
      this.basicData = await countNum(this.actid)
      if(this.act_type == 0 ){
        uni.showToast({ title:'活动未开启', icon:'none' })
        return;
      }else{
        switch (type) {
          case 'share':
            this.showShare = true
            break
          case 'rule':
            this.showRuleModal = true
            break;
          case 'myGuess':
            let callback=()=>{
              uni.navigateTo({
                url: "/plugin/pages/sports/myGuess?id="+this.actid,
              });
            }
            this.getAuth(callback,null,true)
            break;
          case 'mission':
            let back = ()=>{
              this.initTask()

            }
            this.getAuth(back)
            break;
		  case 'sort':
			this.$navigateTo({url:'/plugin/pages/sports/sorts?id='+this.actid})
        }
      }

    },
    hideModal() {
      this.showRuleModal = false
      this.showTask = false
      this.showHelpModal = false
    },
    //关闭广告
    closeAdv() {
      this.advSet.start_ad_show = false
      this.advSet.popup_ad_show = false
    },

    /*登录接口*/
    //所有前置条件
    login(){
      if(this.checkPlat()){
        LoginApp(this.actid)
      }
    },
    //检查平台
    checkPlat(){
      let plat = checkPlatform()
      if(!plat){
        this.$store.dispatch('setGuideShow',4)
      }
      return plat
    },
    async getAuth(callback=()=>{},isNeglect=false){
      let {isWechat,phone} = this.guide
      if(this.checkPlat()){
        let loginStatus = await checkLogin()
        console.info('loginStatus=',loginStatus)
        if(!loginStatus){
          this.login()
          return
        }

        console.info('isQianfan=',isQianfan())
        if(isQianfan()){
          if(!isWechat){
            this.$store.dispatch('setGuideShow',1)
            return
          }
          if(phone==""){
            this.$store.dispatch('setGuideShow',2)
            return
          }
          callback()
        }else{
          callback()
        }
      }
    },
    //被当做iframe引用时处理数据
    setIframeData(){
      let _this = this
      window.addEventListener('message',function(e){
        let data = e.data
        let res = {code:0,data:e.data}
        _this.actid = res.data.slug
        _this.initSportsData(res)
        let {popup} = data
        switch(popup){
          case "task_popup":
            _this.taskMenuData = frameJs.taskMenuData
            _this.showTask=true
            break;
          case "closetask_popup":
            _this.showTask=false
            break;
          default:break;
        }
      })
    },
    jumpNew(url){
      if('' == url || undefined == url){
        return;
      }else{
        window.open(url)
      }

    },
    hideToastModal(){
      this.toastModal = false
    }
  },
  onReachBottom() {

  },
  mounted() {
	  
	if(this.skinType==6){
		this.share_icon=require('@/static/sports/share_act_ny.png')
		this.winner_icon=require('@/static/sports/win_record_ny.png')
		this.rule_icon=require('@/static/sports/act_rules_ny.png')
		this.sort_icon=require('@/static/sports/sorts_icon_ny.png')
		this.guafen_img=require('@/static/sports/sports_win_ny.png')
	}
	  
    this.loading = true
    this.$store.commit('SETACTIVITYNAME','sports')
    this.actid = uni.getStorageSync('actid')
    let web = uni.getStorageSync('WEB') || null
    if (web) {
      /*兼容后台模拟数据*/
      this.isframe = true
      this.setIframeData()
      return
    }

    let code = uni.getStorageSync(this.actid+'Invite') || 0
    if(code != 0 ){
      this.showHelpModal = true
    }
    /*this.initBefore()*/
    this.initSportsData()
  },
}
</script>

<style scoped lang="scss">
@import './worldGuess.scss';

.wordGuess {
  width: 100%;
  min-height: 100vh;
  position: relative;
  overflow-y: hidden;
  .mission_button {
    position: fixed;
    top: 70%;
    right: 10rpx;
    width: 150rpx;
    height: 150rpx;
	z-index: 9;
    transform: translate(0, -50%);

    .mission_img {
      width: 100%;
      height: 100%;
    }
  }

  .right_button {
    position: fixed;
    top: 49rpx;
    right: 30rpx;
	z-index: 9;

    .button_area {
      width: 90rpx;
      height: 90rpx;
      position: relative;
      .red_point{
        width: 20rpx;
        height: 20rpx;
        border-radius: 50%;
        background: red;
        position: absolute;
        top: 4rpx;
        right: 10rpx;
      }
	  .red_point_ny{
		  width: 8rpx;
		  height: 8rpx;
		  background: #F92F2F;
		  top: 50rpx;
		  right: 8rpx;
		  border: 2rpx solid #FFFFFF;
		  z-index: 9;
	  }
      .button_img {
        width: 100%;
        height: 100%;
      }
    }
  }

  .sports_area {
    width: 100%;

    .sports_info {
      margin: 40rpx 70rpx 20rpx 70rpx;
      display: flex;
      justify-content: space-evenly;
      box-sizing: border-box;

      .view_num, .play_num {
        font-size: 24rpx;
        font-weight: 500;
        color: #FFFFFF;

        span {
          font-size: 33rpx;
          padding: 0 15rpx;
        }
      }
    }

    .sports_tab {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin: 20rpx 57rpx 40rpx 57rpx;
      box-sizing: border-box;

      .tab_one {
        width: 206rpx;
        height: 76rpx;
        background: rgba(102, 102, 102, 0.2);
        border-radius: 38px 38px 38px 38px;
        opacity: 1;
        font-size: 30rpx;
        font-weight: bold;
        color: #FFFFFF;
        text-align: center;
        line-height: 76rpx;
      }

      .tab_one_choosed {
        background: #FFFFFF;
        font-size: 30rpx;
        font-weight: 400;
        color: #333333;
      }
	  .new_year_tabcolor{
	  	background: #FFCC4F;
		color: #A13201;
	  	font-size: 30rpx;
	  	font-weight: 400;
	  }
    }

    .sports_list {
      margin: 0 30rpx;
      border-radius: 30rpx;
      .more_button {
        width: 300rpx;
        margin: 50rpx auto 0 auto;
        height: 90rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        background: rgba(100, 100, 100, 0.3);
        border-radius: 300rpx;

        .more_icon {
          width: 70rpx;
          height: 65rpx;
          margin: 0 15rpx 0 0;
        }

        .more_text {
          font-size: 30rpx;
          font-family: PingFang SC-Bold, PingFang SC;
          font-weight: bold;
          color: #FFFFFF;
        }
      }
    }
    .no_sports_list{
      background: #ffffff;
    }
	.service_con{
		margin: 30rpx 0 -20rpx;
	}
    .sports_swiper {
      margin: 50rpx auto 40rpx auto;
      width: 690rpx;
      height: 280rpx;

      .swiper {
        width: 690rpx;
        height: 280rpx;

        .swiper_content {
          width: 100%;
          height: 100%;
          background: #023e49;
          border-radius: 16rpx;
          overflow: hidden;
		  text-align: center;

          .swiper_img {
            width: 100%;
            height: 100%;
          }
		  .swiper_video{
			  width: 690rpx;
			  height: 280rpx;
		  }
        }
      }
    }

    .bottom_text {
      font-size: 30rpx;
      font-family: PingFang SC-Bold, PingFang SC;
      font-weight: bold;
      color: #FFFFFF;
      padding: 50rpx 0 100rpx 0;
      text-align: center;
    }
  }
}
</style>